//
//  JKPostPictureView.m
//  Baisi
//
//  Created by albert on 16/3/21.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKPostPictureView.h"
#import "JKPostModel.h"
#import "UIImageView+WebCache.h"
#import "JKProgressView.h"
#import "JKShowPictureViewController.h"
#import "SVProgressHUD.h"

@interface JKPostPictureView ()
/* 图片 **/
@property (weak, nonatomic) JKAnimatedImageView *pictureImageView;
/* 是否gif **/
@property (weak, nonatomic) IBOutlet UIImageView *gifImageView;
/* 查看大图按钮 **/
@property (weak, nonatomic) IBOutlet UIButton    *seeBigPictureButton;
/* 进度条 **/
@property (weak, nonatomic) IBOutlet JKProgressView *progressView;

/** 裁剪图片的队列 */
@property (nonatomic, strong) dispatch_queue_t clipImageQueue;
@end

@implementation JKPostPictureView

- (dispatch_queue_t)clipImageQueue{
    if (!_clipImageQueue) {
        _clipImageQueue = dispatch_queue_create("clipImageQueue", DISPATCH_QUEUE_CONCURRENT);
    }
    return _clipImageQueue;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    
    JKAnimatedImageView *pictureImageView = [[JKAnimatedImageView alloc] init];
    [self insertSubview:pictureImageView belowSubview:self.gifImageView];
    self.pictureImageView = pictureImageView;
    
    
    //给图片添加点击事件
    self.pictureImageView.userInteractionEnabled = YES;
    [self.pictureImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPicture:)]];
    [self.progressView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showPicture:)]];
    
    //发现控件明明设置好了，但是显示效果却有问题，就有可能是Autoresizing问题
    self.autoresizingMask = UIViewAutoresizingNone;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    self.pictureImageView.frame = self.bounds;
}

//模态窗口显示图片
- (void)showPicture:(UITapGestureRecognizer *)tap{
    
    CGPoint location = [tap locationInView:tap.view];
    
    location = [tap.view convertPoint:location toView:[UIApplication sharedApplication].delegate.window];
    
    [JKShowPictureViewController showWithPost:self.post touchPoint:location sourceVc:nil];
}

- (void)setPost:(JKPostModel *)post{
    _post = post;
    
    //判断是否gif
    //1、根据服务器返回的数据
    //self.gifImageView.hidden = !post.isGif;
    
    //2、根据服务器返回的图片url
    //pathExtension返回字符串最后一个点后面的字符,没有则为返回空字符串
    // abdsdsad.aaa.bbb --> bbb
    NSString *extension = post.large_image.pathExtension;
    // 忽略大写lowercaseString
    BOOL isGif = [extension.lowercaseString isEqualToString:@"gif"];
    self.gifImageView.hidden = !isGif;
    
    //在不知道图片扩展名的情况下，如何知道图片的类型
    //取出图图片数据的第一个字节，就可以判断图片的类型
    //使用SDWebImage的分类NSData+ImageContentType中的方法判断
    
    //是否显示查看大图
    self.seeBigPictureButton.hidden = !post.isPictureTooBig;
    
    if ([[JKPostModel topImageCache] objectForKey:_post.large_image] != nil) {
        
        self.progressView.hidden = YES;
        
        self.pictureImageView.image = [[JKPostModel topImageCache] objectForKey:_post.large_image];
        
        return;
    }
    
    //立刻显示最新的进度值（防止因为网速慢，导致显示的是其它cell图片的下载进度）
    [self.progressView setProgress:post.pictureProgress animated:NO];
    
    //如果是大图片，才需要进行绘图处理
    if (post.isPictureTooBig) {
        
        UIImage *image = [[SDWebImageManager sharedManager].imageCache imageFromDiskCacheForKey:post.large_image];
        
        if (image) {
            
            [self clipTopImage:image];
            
            return;
        }
    }
    
    //图片显示
    [self.pictureImageView fl_setImageWithURL:[NSURL URLWithString:post.large_image] placeholderImage:nil options:!post.isPictureTooBig ? 0 : SDWebImageAvoidAutoSetImage progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //进度，把 1.0 放在后面没有效果？？
            self.post.pictureProgress = 1.0 * receivedSize / expectedSize;
            
            //显示进度条
            self.progressView.hidden = NO;
            
            //设置进度条
            [self.progressView setProgress:self.post.pictureProgress animated:NO];
        });
        
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        //完成后隐藏进度条
        self.progressView.hidden = YES;
        
//        if (isGif) {
//
//            FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:[NSData dataWithContentsOfFile:[[SDWebImageManager sharedManager].imageCache defaultCachePathForKey:imageURL.absoluteString]]];
//
//            self.pictureImageView.animatedImage = animatedImage;
//
//            return;
//        }
        
        //如果是大图片，才需要进行绘图处理
        if (self.post.isPictureTooBig) {
            
            [self clipTopImage:image];
            
            return;
        }
    }];
}

- (void)clipTopImage:(UIImage *)image{
    
    //完成后隐藏进度条
    self.progressView.hidden = YES;
    
    dispatch_async(self.clipImageQueue, ^{
        
        NSString *url = self.post.large_image;
        
        //开启图形上下文，将图片画在pictureFrame的尺寸，YES表示不透明
        UIGraphicsBeginImageContextWithOptions(self.post.pictureFrame.size, YES, 0.0);
        
        //将下载好的image对象绘制到图形上下文
        CGFloat width = self.post.pictureFrame.size.width;
        CGFloat height = width * image.size.height / image.size.width;
        [image drawInRect:CGRectMake(0, 0, width, height)];
        
        UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
        
        //结束图形上下文
        UIGraphicsEndImageContext();
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[JKPostModel topImageCache] setObject:img forKey:url];
            
            if (![url isEqualToString:self.post.large_image]) {
                
                JKLog(@"截取图片url不一致被拦截！！！");
                
                return;
            }
            
            //获得图片
            self.pictureImageView.image = img;
        });
    });
}
@end
